﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;

public class DeferredSynchronizeInvoke : ISynchronizeInvoke
{
    private Queue<UnityAsyncResult> fifoToExecute = new Queue<UnityAsyncResult>();
    private Thread mainThread = Thread.CurrentThread;

    public IAsyncResult BeginInvoke(Delegate method, object[] args)
    {
        UnityAsyncResult item = new UnityAsyncResult {
            method = method,
            args = args,
            IsCompleted = false,
            AsyncWaitHandle = new ManualResetEvent(false)
        };
        Queue<UnityAsyncResult> fifoToExecute = this.fifoToExecute;
        lock (fifoToExecute)
        {
            this.fifoToExecute.Enqueue(item);
        }
        return item;
    }

    public object EndInvoke(IAsyncResult result)
    {
        if (!result.IsCompleted)
        {
            result.AsyncWaitHandle.WaitOne();
        }
        return result.AsyncState;
    }

    public object Invoke(Delegate method, object[] args)
    {
        if (this.InvokeRequired)
        {
            IAsyncResult result = this.BeginInvoke(method, args);
            return this.EndInvoke(result);
        }
        return method.DynamicInvoke(args);
    }

    public void ProcessQueue()
    {
        if (Thread.CurrentThread != this.mainThread)
        {
            object[] objArray1 = new object[] { base.GetType(), ".", MethodBase.GetCurrentMethod().Name, "() must be called from the same thread it was created on (created on thread id: ", this.mainThread.ManagedThreadId, ", called from thread id: ", Thread.CurrentThread.ManagedThreadId };
            throw new TargetException(string.Concat(objArray1));
        }
        bool flag = true;
        UnityAsyncResult result = null;
        while (flag)
        {
            Queue<UnityAsyncResult> fifoToExecute = this.fifoToExecute;
            lock (fifoToExecute)
            {
                if (this.fifoToExecute.Count <= 0)
                {
                    break;
                }
                result = this.fifoToExecute.Dequeue();
            }
            result.AsyncState = this.Invoke(result.method, result.args);
            result.IsCompleted = true;
        }
    }

    public bool InvokeRequired
    {
        get
        {
            return (this.mainThread.ManagedThreadId != Thread.CurrentThread.ManagedThreadId);
        }
    }

    private class UnityAsyncResult : IAsyncResult
    {
        public object[] args;
        public Delegate method;

        public object AsyncState { get; set; }

        public WaitHandle AsyncWaitHandle { get; internal set; }

        public bool CompletedSynchronously
        {
            get
            {
                return this.IsCompleted;
            }
        }

        public bool IsCompleted { get; set; }
    }
}

